#pragma once 
#include <iostream>
#include <pthread.h>
#include <signal.h>

#include "TcpServer.hpp"
#include "Log.hpp"
#include "Task.hpp"
#include "ThreadPool.hpp"

#define PORT 8080
class HttpServer{
  private:
    bool stop_;
    int port_;

  public:
    HttpServer(int port = PORT):port_(port), stop_(false)
      {}
    void InitServer(){
      //信号SIGPIPE需要进行忽略，如果不忽略，再写入时，可能直接崩溃server
      //这是向客户端写入过程可能出现的错误
      signal(SIGPIPE, SIG_IGN);
    }
    void Loop(){
      LOG(INFO, "Loop begin!");
      while(!stop_){
        TcpServer* tsvr = TcpServer::getInstance(port_);
  
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int sock  = accept(tsvr->Sock(), (struct sockaddr*)&peer, &len);
        if(sock < 0){
          continue;
        }
        LOG(INFO, "get a new link!");

        Task t(sock);
        ThreadPool::GetInstance()->PushTask(t);
      }
    }
    ~HttpServer()
      {}

};
